package com.fg.estate.service.impl;

import com.fg.estate.bean.Admin;
import com.fg.estate.mapper.AdminMapper;
import com.fg.estate.service.AdminService;
import com.fg.estate.util.SecurityUils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author 丰哥
 * 2022/10/13
 *
 * 管理员业务层实现
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public List<Map<String, Object>> selectAllAdminAndRoles() throws Exception {
        return adminMapper.selectAllAdminAndRoles();
    }

    @Override
    public void insert(Admin admin) throws Exception {
        adminMapper.insert(admin);
    }

    @Override
    public Admin login(String username, String password) throws Exception {
        // 登录校验
        // ① 根据用户名查询用户数据
        Admin admin = adminMapper.selectByUsername(username);

        // ② 根据数据的密文密码和明文密码匹配
        if(admin != null) {
            String mPassword = SecurityUils.getMD5Password(password, admin.getSalt());
            if(mPassword.equals(admin.getPassword())) {
                return admin;
            }
        }

        return null;
    }

    @Override
    public PageInfo<Map<String, Object>> getPageInfo(int pageNum, int pageSize) throws Exception {

        PageHelper.startPage(pageNum, pageSize);

        List<Map<String, Object>> adminAndRoles = adminMapper.selectAllAdminAndRoles();
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(adminAndRoles);

        return pageInfo;
    }
}
